const wifi = {
	SSID: '',
	PWD: '',
	func: null,
	index: 1,
	resolve: null,
	reject: null,

	init(SSID = '', PWD = '') {
		// sb微信小程序try catch监听不到异常
		return new Promise((resolve, reject) => {
			this.resolve = resolve
			this.reject = reject

			this.index = 1
			if (!SSID) reject('请输入Wi-Fi名')
			if (!PWD) reject('请输入Wi-Fi密码')
			this.SSID = SSID
			this.PWD = PWD
			this.getSystemInfo()
		})
	},
	getSystemInfo() {
		uni.getSystemInfo({
			success: (res) => {
				if (!res.wifiEnabled) {
					this.reject('请先打开Wi-Fi')
				}
				var system = '';
				if (res.platform == 'android') system = parseInt(res.system.substr(8));
				if (res.platform == 'ios') system = parseInt(res.system.substr(4));
				if (res.platform == 'android' && system < 6) {
					this.reject('手机版本不支持')
				}
				if (res.platform == 'ios' && system < 11.2) {
					this.reject('手机版本不支持')
				}
				this.start()
			}
		})
	},
	start() {
		console.log('-=-=-=start')
		uni.startWifi({
			success: res => {
				this.connected()
			},
			fail: err => {
				this.reject(err.errMsg)
			}
		})
	},
	connected() {
		uni.onWifiConnected(res => {
			if (this.index !== 1) return
			this.index++
			if (!!res.wifi.SSID) {
				this.resolve('已连接Wi-Fi')
			} else {
				this.getList()
			}
		})
	},
	getList() {
		uni.getWifiList({
			success: res => {
				uni.onGetWifiList(res => {
					let wifi = res.wifiList.find(v => {
						return v.SSID == this.SSID
					})
					if (!wifi) {
						this.reject('未找到Wi-Fi')
					}
					this.connect()
				})
			}
		})
	},
	connect() {
		uni.connectWifi({
			SSID: this.SSID,
			password: this.PWD,
			success: res => {
				this.resolve('链接成功')
			},
			fail: err => {
				let msg = ''
				if (err.errCode == 12010) {
					this.reject('系统错误，试试其他Wi-Fi吧')
				}
				if (!msg) this.reject('未知错误')
				this.reject(msg)
			},
			complete: com => {
				// uni.hideLoading()
			}
		})
	},
	msg(title, icon = 'error') {
		uni.showToast({
			title,
			icon
		})
	}
}
export default wifi